package org.jeecg.modules.achexaminationpaper.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.achachievementstandard.entity.AchAchievementStandard;
import org.jeecg.modules.achachievementstandard.service.IAchAchievementStandardService;
import org.jeecg.modules.achachievestandarditem.entity.AchAchieveStandardItem;
import org.jeecg.modules.achachievestandarditem.service.IAchAchieveStandardItemService;
import org.jeecg.modules.achachievestandarditem.vo.AchAchieveStandardItemVo;
import org.jeecg.modules.achexaminationpaper.entity.AchExaminationPaper;
import org.jeecg.modules.achexaminationpaper.service.IAchExaminationPaperService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.achexaminationpaper.vo.AchExaminationPaperVo;
import org.jeecg.modules.achexampaperprojectitem.entity.AchExamPaperProjectItem;
import org.jeecg.modules.achexampaperprojectitem.service.IAchExamPaperProjectItemService;
import org.jeecg.modules.common.api.ISysInfo;
import org.jeecg.modules.common.baseentity.BaseApiEntity;
import org.jeecg.modules.relation.relachstandarddistribution.entity.RelAchStandardDistribution;
import org.jeecg.modules.relation.relachstandarddistribution.service.IRelAchStandardDistributionService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: ach_examination_paper
 * @author: baochangrong
 * @Date: 2022-03-15
 * @Version: V1.0
 */
@Api(tags = "ach_examination_paper")
@RestController
@RequestMapping("/achexaminationpaper/achExaminationPaper")
@Slf4j
public class AchExaminationPaperController extends JeecgController<AchExaminationPaper, IAchExaminationPaperService> {
    @Autowired
    private IAchExaminationPaperService achExaminationPaperService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private ISysInfo sysInfo;
    /**
     * 试卷分项
     */
    @Autowired
    private IAchExamPaperProjectItemService achExamPaperProjectItemService;
    /**
     * 标准
     */
    @Autowired
    private IAchAchievementStandardService achAchievementStandardService;
    /**
     * 试卷 标准关系
     */
    @Autowired
    private IRelAchStandardDistributionService relAchStandardDistributionService;
    /**
     * 标准明细
     */
    @Autowired
    private IAchAchieveStandardItemService achAchieveStandardItemService;


    /**
     * 分页列表查询
     *
     * @param achExaminationPaper
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "ach_examination_paper-分页列表查询")
    @ApiOperation(value = "ach_examination_paper-分页列表查询", notes = "ach_examination_paper-分页列表查询")
    @GetMapping(value = "/list2")
    public Result<?> queryPageList(AchExaminationPaper achExaminationPaper,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        Map<String,String> queryParam = sysInfo.getMapQueryParamByReq(req);
        //获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值克隆给vo
        BaseApiEntity baseApiEntity = sysInfo.querySysInfoCloneObj(req,achExaminationPaper,false); //获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值给vo
        achExaminationPaper.setCreateBy(null);
        achExaminationPaper.setCreateTime(null);
        achExaminationPaper.setUpdateBy(null);
        achExaminationPaper.setUpdateTime(null);
        QueryWrapper<AchExaminationPaper> queryWrapper = QueryGenerator.initQueryWrapper(achExaminationPaper, req.getParameterMap());
        Page<AchExaminationPaper> page = new Page<AchExaminationPaper>(pageNo, pageSize);
        IPage<AchExaminationPaper> pageList = achExaminationPaperService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 查询全部考试试卷 分页查询
     */
    @AutoLog(value = "getAchExaminationPaperList-分页列表查询")
    @ApiOperation(value = "getAchExaminationPaperList-分页列表查询", notes = "getAchExaminationPaperList-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> getAchExaminationPaperList(@Param("AchExaminationPaperVo") AchExaminationPaperVo achExaminationPaperVo,
                                                @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                HttpServletRequest req) {
        //组装查询参数
        //组装vo以外的其他参数
        Map<String,String> queryParam = sysInfo.getMapQueryParamByReq(req);
        //获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值克隆给vo
        BaseApiEntity baseApiEntity = sysInfo.querySysInfoCloneObj(req,achExaminationPaperVo,false); //获取当前登录用户信息 把租户 部门 身份 学期 学年等基本信息信息赋值给vo
        achExaminationPaperVo.setCreateBy(null);
        achExaminationPaperVo.setCreateTime(null);
        achExaminationPaperVo.setUpdateBy(null);
        achExaminationPaperVo.setUpdateTime(null);

        Page<AchExaminationPaperVo> page = new Page<AchExaminationPaperVo>(pageNo, pageSize);
        IPage<AchExaminationPaperVo> achExaminationPaperList = achExaminationPaperService.getAchExaminationPaperList(page, achExaminationPaperVo);
        return Result.OK(achExaminationPaperList);
    }


    /**
     * 添加
     *
     * @param achExaminationPaper
     * @return
     */
    @AutoLog(value = "ach_examination_paper-添加")
    @ApiOperation(value = "ach_examination_paper-添加", notes = "ach_examination_paper-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody AchExaminationPaper achExaminationPaper, HttpServletRequest req) {
        //获取当前登录用户信息
        String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        //		SysUser sysUser = sysUserService.getOneUser(username);// sysBaseAPI.getUserByName(username); 不能直接引用system模块，需使用APi调用
        LoginUser loginUser = sysBaseAPI.getUserByName(username); //.getUserById() 获取登录用户
        String tenantId = req.getHeader("tenant-id");//获取当前登录用户的租户id
        String sysOrgCode = loginUser.getOrgCode();//获取当前用户的当前的部门编码（不是id是编码）,该编码随前端切换

        achExaminationPaper.setTenantId(tenantId);
        achExaminationPaper.setSysOrgCode(sysOrgCode);
        achExaminationPaperService.save(achExaminationPaper);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param achExaminationPaper
     * @return
     */
    @AutoLog(value = "ach_examination_paper-编辑")
    @ApiOperation(value = "ach_examination_paper-编辑", notes = "ach_examination_paper-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody AchExaminationPaper achExaminationPaper) {
        achExaminationPaperService.updateById(achExaminationPaper);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ach_examination_paper-通过id删除")
    @ApiOperation(value = "ach_examination_paper-通过id删除", notes = "ach_examination_paper-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        achExaminationPaperService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "ach_examination_paper-批量删除")
    @ApiOperation(value = "ach_examination_paper-批量删除", notes = "ach_examination_paper-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.achExaminationPaperService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "ach_examination_paper-通过id查询")
    @ApiOperation(value = "ach_examination_paper-通过id查询", notes = "ach_examination_paper-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        AchExaminationPaper achExaminationPaper = achExaminationPaperService.getById(id);
        if (achExaminationPaper == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(achExaminationPaper);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param achExaminationPaper
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, AchExaminationPaper achExaminationPaper) {
        return super.exportXls(request, achExaminationPaper, AchExaminationPaper.class, "ach_examination_paper");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, AchExaminationPaper.class);
    }

    /**
     * 复制试卷 快速生成试卷
     * copyCreateAchExamPaper
     **/
    @AutoLog(value = "copyCreateAchExamPaper-复制试卷")
    @ApiOperation(value = "copyCreateAchExamPaper-复制试卷", notes = "copyCreateAchExamPaper-复制试卷")
    @PostMapping(value = "/copyCreateAchExamPaper")
    public Result<?> copyCreateAchExamPaper(@RequestBody AchExaminationPaper oldAchExaminationPaper,
                                            HttpServletRequest req) {
        //获取当前登录用户信息
        String token = req.getHeader(CommonConstant.X_ACCESS_TOKEN);
        String username = JwtUtil.getUsername(token);
        //        SysUser sysUser = sysUserService.getOneUser(username);// sysBaseAPI.getUserByName(username); 不能直接引用system模块，需使用APi调用
        LoginUser loginUser = sysBaseAPI.getUserByName(username); //.getUserById() 获取登录用户
        String tenantId = req.getHeader("tenant-id");//获取当前登录用户的租户id
        String sysOrgCode = loginUser.getOrgCode();//获取当前用户的当前的部门编码（不是id是编码）,该编码随前端切换
        String departId = sysBaseAPI.getDepartIdsByOrgCode(sysOrgCode);//获取当前用户设置的部门id
        List<String> subDepIdsList = sysBaseAPI.getSubDepIdsByDepId(departId); //获取下级部门的部门id，自定义改造sysBaseAPI
        String subDepSysOrgCodes = sysBaseAPI.getSubDepOrgCodesByDepId(departId); //直接获取下级部门的orgcode，自定义改造sysBaseAPI
        //userIdentity 用户身份字典码user_identity， 3教师 4学生 1普通用户 2上级部门负责人 5家长 6班级
        int userIdentity = loginUser.getUserIdentity();//获取当前登录用户身份：字典码 user_identity
        //=========================================
        return achExaminationPaperService.copyAchExaminationPaper(oldAchExaminationPaper);
    }

    /**
     * 试卷list paperList
     */
    @AutoLog(value = "getAchExaminationPaperList-列表查询")
    @ApiOperation(value = "getAchExaminationPaperList-列表查询", notes = "getAchExaminationPaperList-列表查询")
    @GetMapping(value = "/paperList")
    public Result<?> paperList(AchExaminationPaper achExaminationPaper, HttpServletRequest req) {
        List<AchExaminationPaper> achExaminationPaperList = achExaminationPaperService.list(new QueryWrapper<AchExaminationPaper>(achExaminationPaper));
        return Result.OK(achExaminationPaperList);
    }

}
